package com.atww.back.controller;

import com.atww.back.domain.dto.OrderPageDto;
import com.atww.back.domain.pojo.Order;
import com.atww.back.domain.pojo.ParkingLot;
import com.atww.back.domain.pojo.ParkingSpace;
import com.atww.back.domain.pojo.User;
import com.atww.back.domain.vo.ResultVo;
import com.atww.back.service.OrderService;
import com.atww.back.service.ParkingLotService;
import com.atww.back.service.ParkingSpaceService;
import com.atww.back.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {


    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;
    @Autowired
    ParkingSpaceService spaceService;

    @Autowired
    ParkingLotService lotService;



    @PostMapping
    @Transactional
    public ResultVo saveOrUpdate(@RequestBody Order order){
        //拿到price
        long time = order.getDepartureTime().getTime() - order.getArrivalTime().getTime();
        long hours=time/3600000;
        order.setPrice(BigDecimal.valueOf(10*hours));
        //拿到userId
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,order.getUserName());
        User user = userService.getOne(queryWrapper);
        order.setUserId(user.getId());
        //更改车位状态
        LambdaQueryWrapper<ParkingSpace> spaceLambdaQueryWrapper=new LambdaQueryWrapper<>();
        spaceLambdaQueryWrapper.eq(ParkingSpace::getId,order.getParkingSpaceId());
        ParkingSpace parkingSpace = spaceService.getOne(spaceLambdaQueryWrapper);
        parkingSpace.setStatus(2);
        spaceService.updateById(parkingSpace);
        orderService.saveOrUpdate(order);
        return ResultVo.success("",order.getUserId());
    }

    @DeleteMapping("/{id}")
    public ResultVo del(@PathVariable Integer id){
        orderService.removeById(id);
        return ResultVo.success();
    }

    @PostMapping("/page")
    public ResultVo getPage(@RequestParam(required = false) String userId,
                            @RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = ""+ Integer.MAX_VALUE) Integer pageSize) {

        LambdaQueryWrapper<Order> queryWrapper= new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(userId)) {
            queryWrapper.eq(Order::getUserId,userId);
        }
        queryWrapper.orderByDesc(Order::getCreatetime);
        Page<Order> page = orderService.page(new Page<>(pageNum, pageSize), queryWrapper);
        page.getRecords().stream().map( m ->{
            m.setUserName(userService.getById(m.getUserId()).getName());
            m.setParkingLotName(lotService.getById(m.getParkingLotId()).getName());
            m.setParkingSpaceName(spaceService.getById(m.getParkingSpaceId()).getName());

            return m;
        }).collect(Collectors.toList());
        return ResultVo.success("",page);

    }

    @PostMapping("/getPage/{pageCount}")
    public ResultVo getPage(@PathVariable Integer pageCount, @RequestBody OrderPageDto pageDto){
       //如果有userName则查询用户并判断是否是车库管理员，若是则条件用PrincipalId，不是则用userId
        if(StringUtils.hasText(pageDto.getUserName())){
            LambdaQueryWrapper<User> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(User::getUsername,pageDto.getUserName());
            User user = userService.getOne(queryWrapper1);
            if(user.getType()==2){
                pageDto.setPrincipalId(user.getId());
                pageDto.setUserId(0);
            }else if(user.getType()==1){
                pageDto.setUserId(user.getId());
            }
        }

        Page page=orderService.getPage(pageCount,pageDto);
        return ResultVo.success("",page);
    }

    @GetMapping("/getSpace/{lotId}")
    public ResultVo getSpace(@PathVariable Integer lotId){
        LambdaQueryWrapper<ParkingSpace> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkingSpace::getParkingLotId,lotId);
        queryWrapper.eq(ParkingSpace::getStatus,1);
        List<ParkingSpace> spaceList = spaceService.list(queryWrapper);
        return ResultVo.success("",spaceList);
    }

    @PostMapping("/change/{id}/{psId}/{uname}")
    @Transactional
    public ResultVo change(@PathVariable Integer id,@PathVariable Integer psId,@PathVariable String uname){
        LambdaQueryWrapper<User> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getUsername,uname);
        User user = userService.getOne(queryWrapper1);
        Order order = orderService.getById(id);
        if(!Objects.equals(order.getUserId(), user.getId())){
            return ResultVo.fail("无法操作他人订单！");
        }
        order.setStatus(1);
        orderService.updateById(order);
        ParkingSpace parkingSpace = spaceService.getById(psId);
        parkingSpace.setStatus(1);
        spaceService.updateById(parkingSpace);
        return ResultVo.success();
    }


}
